package com.example.acitividemo2.config;

import cn.hutool.core.util.ArrayUtil;
import com.example.acitividemo2.annotation.BeanOverride;
import com.example.acitividemo2.util.BeanOverrideUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class ManageBean implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        ConfigurableListableBeanFactory registry = (ConfigurableListableBeanFactory) beanDefinitionRegistry;
        String[] beanDefinitionNames = registry.getBeanDefinitionNames();
        List<String> removeBeanNames = new ArrayList<>();
        for (String beanDefinitionName : beanDefinitionNames) {
            BeanOverride beanOverride = registry.findAnnotationOnBean(beanDefinitionName, BeanOverride.class);
            if (beanOverride == null) {
                continue;
            }
            Class<?>[] overrideClasses = beanOverride.value();
            String overrideName = beanOverride.name();
            if (!overrideName.trim().equals("")) {
                removeBeanNames.add(overrideName);
            }
            if (overrideClasses.length > 0) {
                for (Class<?> overrideClass : overrideClasses) {
                    String[] types = registry.getBeanNamesForType(overrideClass);
                    for (String type : types) {
                        if (!beanDefinitionName.equals(type)) {
                            removeBeanNames.add(type);
                        }
                    }
                }
            }
            if (overrideName.trim().equals("") && overrideClasses.length == 0) {
                removeBeanNames.addAll(BeanOverrideUtils.guessOverrideBean(beanDefinitionName, beanDefinitionRegistry, beanOverride.limit()));
            }
        }
        BeanOverrideUtils.removeBean(beanDefinitionRegistry, removeBeanNames);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }

}
